package test.proxy;

import com.google.common.collect.ImmutableMap;
import org.mitre.dsmiley.httpproxy.ProxyServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.servlet.Servlet;
import java.util.Map;

/**
 * @Classname ProxyServletConfiguration
 * @Description TODO 实现代理配置
 * @Date 2022/3/28 11:23
 * @Created by KangJonney
 */
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class})
@Configuration
public class ProxyServletConfiguration {
    // 读取配置文件中路由设置
    @org.springframework.beans.factory.annotation.Value("${proxy.servlet_url}")
    private String servletUrl;

    // 读取配置中代理目标地址
    @org.springframework.beans.factory.annotation.Value("${proxy.target_url}")
    private String targetUrl;

    @Bean
    public Servlet createProxyServlet() {
        // 创建新的ProxyServlet
        return new ProxyServlet();
    }

    @Bean
    public ServletRegistrationBean proxyServletRegistration() {
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(createProxyServlet(), servletUrl);
        //设置网址以及参数
        Map<String, String> params = ImmutableMap.of(
                "targetUri", targetUrl,
                "log", "true");
        registrationBean.setInitParameters(params);
        return registrationBean;
    }

    @PostConstruct
    public void setUsePingMethod(){
        System.setProperty("druid.mysql.usePingMethod", "false");
    }

    public static void main(String[] args) {
        SpringApplication.run(ProxyServletConfiguration.class, args);
    }

}
